# coding:utf-8
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.http import JsonResponse
from models import User, Article, Comment, Follow, Like,UserImage,Type,Article_to_type,Collect,Leave
import json
from django.db.models.query import Q
import copy
import os
from PIL import Image
from datetime import *
import time as timee
import random
import hashlib
from forms import RegisterForm, LoginForm, UserForm
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.decorators import login_required
from bs4 import BeautifulSoup

PAGE_SIZE = 10



def home(request):
    articles = Article.objects.get_hot_article()
    hot_smalls = []
    hot_big = None
    for article in articles:
        if hot_big is None:
            hot_big = article
        else:
            hot_smalls.append(article)
    return render(request, 'home.html',{'hot_big':hot_big,'hot_smalls':hot_smalls})




def discover(request):
    return render(request, 'discover.html')


def leave(request):
    if request.method == "POST":
        user = request.user
        if not user.is_authenticated():
            user = None
        text = request.POST.get('text', '')
        leave = Leave(user=user, text=text)
        leave.save()
        leaves = Leave.objects.all().order_by('-pub_date')
        return render(request, 'leave.html',{'leaves':leaves})
    else:
        leaves = Leave.objects.all()
        return render(request, 'leave.html',{'leaves':leaves})

@login_required
def publish(request):
    types = Type.objects.all()
    return render(request, 'publish.html',{'types':types})

@login_required
def edit(request):
    if request.method == 'GET':
        if request.user:
            return render(request, 'edit.html', {'user': request.user})
        else:
            return HttpResponse('发生了意想不到的错误')
    else:
        name = request.POST.get('name', '')
        text = request.POST.get('text', '')
        if request.user:
            request.user.name = name
            request.user.text = text
            file = request.FILES.get('icon', None)
            if file:
                request.user.icon = file
            request.user.save()
            return redirect('/user/' + request.user.username)


def getArticleById(request, articleId):
    article = Article.objects.get(id=articleId);
    article.hot = article.hot + 1
    article.save()
    article.auther.get_following(request)
    article.get_like(request)
    article.get_collect(request)
    recommends = Article.objects.get_recommend_article()
    return render(request, 'articledetail.html',{'article': article,
                                                 'recommends':recommends,
                                                 'comments':article.get_comments()
                                                 })


def login_page(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    else:
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(username=username,password=password)
            if user is not None:
                login(request,user)
                response = redirect('/', {'user': user})
                return response
            else:
                return render(request, 'login.html', {'help': '用户名或密码不正确'})
        else:
            return render(request, 'register.html', {'form': form})

def user_logout(request):
    logout(request)
    return redirect('/')


def register_page(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    else:
        register = RegisterForm(request.POST)
        if register.is_valid():
            username = register.cleaned_data['username']
            password = register.cleaned_data['password']
            user = User.objects.filter(username=username)
            if user:
                return render(request, 'register.html', {'help': '用户名已存在'})
            user = User(username=username, name=username)
            user.set_password(password)
            user.save()
            return redirect('/login/')
        else:
            return render(request, 'register.html', {'form': register})


@login_required
def uploadImage(request):
    file = request.FILES.get('image', None)
    user_image = UserImage(user=request.user)
    user_image.image = file
    user_image.save()
    user_image.thumb_image = user_image.make_thumb()
    user_image.save()
    url = '/media/%s'%(user_image.image)
    return HttpResponse(url)


def createArticle(request):
    # body =  json.loads(request.body.decode())
    user = request.user
    if user.is_authenticated():
        title = request.POST.get('title', ' ')
        content = request.POST.get('content', ' ')
        tags = request.POST.getlist('tags[]')

        imgs = []
        thumbs = []
        bs = BeautifulSoup(content)
        for img in bs.find_all('img'):
            src = img.get('src')
            thumb_all_name = src.split('/')
            ext = thumb_all_name[-1].split('.')[-1]
            name = thumb_all_name[-1].split('.')[0]+'_thumb'
            del thumb_all_name[-1]
            thumb_path = '/'.join(thumb_all_name)+'/'+name+'.'+ext
            imgs.append(src)
            thumbs.append(thumb_path)
        article = Article()
        article.images = ';'.join(imgs)
        article.thumb_images = ';'.join(thumbs)
        article.auther = user
        article.title = title
        article.content = content
        article.create_date = datetime.now()
        article.save()
        url = "/article/%s/" % article.id
        tag_text = ''
        for tag in tags:
            article_to_type = Article_to_type(article_id=article,type_id_id=tag)
            article_to_type.save()
            tag_text = tag_text +' '+ article_to_type.type_id.name
        article.tag_text = tag_text
        article.save()
        return HttpResponse(url)
    return HttpResponse('fail')


def comment(request):
    user = request.user
    if not user.is_authenticated():
        user = None
    text = request.POST.get('text', '')
    article_id = request.POST.get('article_id', '')
    time = datetime.now()
    comment = Comment(user=user, text=text, pub_date=time, article_id=article_id)
    comment.save()
    return redirect('/article/%s/' % article_id)



def imagesPage(request):
    page = int(request.GET.get('page', 0))
    articles = Article.objects.order_by('-create_date')[page*PAGE_SIZE:page*PAGE_SIZE+PAGE_SIZE]
    if articles:
        return render(request, "images.html", {'articles': articles})
    else:
        return HttpResponse('fail')


def hot_images(request):
    page = int(request.GET.get('page', 0))
    articles = Article.objects.order_by('-hot')[5+page*PAGE_SIZE:5+page*PAGE_SIZE+PAGE_SIZE]
    if articles:
        return render(request, "images.html", {'articles': articles})
    else:
        return HttpResponse('fail')


# ====================================userinfo======================================
def user(request, username):
    user = User.objects.filter(username=username).first()
    user.get_following(request)
    articles = Article.objects.filter(auther__username=username).order_by('-create_date')
    return render(request, 'user.html', {'user_all': user,'articles':articles})

def likes(request,username):
    user = User.objects.filter(username=username).first()
    likes = Like.objects.filter(user=user)
    return render(request, 'user_likes.html', {'user_all':user,'likes':likes})


def collects(request,username):
    user = User.objects.filter(username=username).first()
    collects = Collect.objects.filter(user=user)
    return render(request, 'user_collects.html', {'user_all':user,'collects':collects})


def fans(request,username):
    user = User.objects.filter(username=username).first()
    user.get_following(request)
    fans = Follow.objects.filter(to_user__id=user.id)
    users = []
    has_fans = False
    for fan in fans:
        users.append(fan.from_user)
        fan.from_user.get_following(request)
        has_fans = True
    return render(request, 'user_fans.html', {'user_all':user,'users': users,'has_fans':has_fans})


def follows(request,username):
    user = User.objects.filter(username=username).first()
    user.get_following(request)
    fans = Follow.objects.filter(from_user__id=user.id)
    users = []
    has_follows = False
    for fan in fans:
        users.append(fan.to_user)
        fan.to_user.get_following(request)
        has_follows = True
    return render(request, 'user_follow.html', {'user_all':user,'users': users,'has_follows':has_follows})


# ====================================action======================================
def action_like(request):
    article_id = request.POST.get('article_id', '')
    if request.user.is_authenticated():
        like = Like(user=request.user,article_id=article_id)
    else:
        like = Like(article_id=article_id)
    like.save()
    return HttpResponse(200)


def action_unlike(request):
    if request.user.is_authenticated():
        article_id = request.POST.get('article_id', '')
        like = Like.objects.filter(user=request.user, article_id=article_id).first()
        like.delete()
        return HttpResponse(200)
    else:
        return HttpResponse(200)

@login_required
def action_collect(request):
    if request.user.is_authenticated():
        article_id = request.POST.get('article_id', '')
        collect = Collect(user=request.user,article_id=article_id)
        collect.save()
        return HttpResponse(200)
    else:
        return HttpResponse(404)


@login_required
def action_uncollect(request):
    if request.user.is_authenticated():
        article_id = request.POST.get('article_id', '')
        collect = Collect.objects.filter(user=request.user, article_id=article_id).first()
        collect.delete()
        return HttpResponse(200)
    else:
        return HttpResponse(404)


@login_required
def action_follow(request):
    user = request.user
    user_id = request.POST.get('user_id', '')
    if user.is_authenticated():
        new_follow = Follow(from_user_id=user.id, to_user_id=user_id, relation=False)
        new_follow.save()

        follow = Follow.objects.filter(Q(from_user__id=user_id) & Q(to_user__id=user.id)).first()
        if follow:
            follow.relation = True
            follow.save()
            new_follow.relation = True
            follow.save()
        return HttpResponse(200)
    else:
        return HttpResponse(404)

@login_required
def action_unfollow(request):
    user = request.user
    user_id = request.POST.get('user_id', '')
    if user:
        follow = Follow.objects.filter(Q(from_user__id=user.id) & Q(to_user__id=user_id)).first()
        if follow.relation:
            nfollow = Follow.objects.filter(Q(from_user__id=user_id) & Q(to_user__id=user.id)).first()
            nfollow.relation = False
            nfollow.save()
        follow.delete()
        return HttpResponse(200)




# ====================================type======================================

def type(request):
    types = Type.objects.all()
    return render(request, 'type.html',{'types':types})

def list_type(request):
    types = Type.objects.all()
    for type in types:
        type.article_count = Article_to_type.objects.filter(type_id=type).count()
    return render(request,'type.html',{'types':types})

@login_required
def create_type(request):
    if request.method == 'GET':
        return render(request,'type_edit.html')
    else:
        user = request.user
        if user.is_superuser:
            name = request.POST.get('name','')
            icon = request.FILES.get('image',None)
            type = Type(name=name)
            type.image = icon
            type.save()
            return redirect('/type/')
        return HttpResponse(status=404)

def articles_by_type(request,type_id):
    if request.method == 'POST':
        page = int(request.POST.get('page',''))
        type = Type.objects.get(id=type_id)
        type.hot = type.hot + 1
        type.save()
        article_to_type = Article_to_type.objects.filter(type_id_id=type_id)[page*PAGE_SIZE:(page+1)*PAGE_SIZE]
        if not article_to_type:
            return HttpResponse('fail')
        articlelist = []
        for article in article_to_type:
            art = article.article_id
            articlelist.append(art)
        return render(request,'images.html',{'articles':articlelist})
    else:
        return render(request,'articles.html')


# ====================================hot======================================
# @login_required
# def create_hot(request):
#     user = request.user
#     if user.username == 'a6431065':
#         article_id = request.POST.get('article_id','')
#         hot = HotArticle(article_id=article_id)
#         hot.save()
#         return HttpResponse(200)
#
# def get_hots():
#     hots = HotArticle.objects.all().order_by('-sign_date')[:5]

